package user

import (
	"fmt"
	"time"

	"clouds.lgb24kcs.cn/controllers/user/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/oss"
	"github.com/gin-gonic/gin"
)

type RegisterFunc struct {
}

var RegisterAPI RegisterFunc

/*用户注册完后，直接在存储空间中创建一个与用户名相同的存储空间*/
func (r *RegisterFunc) Register(c *gin.Context, req request.RegisterReq) {
	user := models.User{
		Username: req.Username,
		Password: req.Password,
		Mobile:   req.Mobile,
	}
	err := global.APP.DB.Create(&user).Error
	if err != nil {
		global.APP.Log.Error(err.Error())
		utils.Fail(c, errorx.UserRegister, err.Error())
	} else {
		userInfo := request.RegisterRes{
			Id:       int64(user.ID),
			Username: user.Username,
			Mobile:   user.Mobile,
			Create:   user.CreatedAt.Format(time.DateTime),
		}
		storageAPI := oss.OSS{}
		client := storageAPI.NewClient(global.APP.Configuration.Minio.AccessKey, global.APP.Configuration.Minio.SecretKey, global.APP.Configuration.Minio.Zone)
		err := storageAPI.CreateBucket(client, global.APP.Configuration.Minio.BucketName)
		if err != nil {
			global.APP.Log.Error(fmt.Sprintf("minio初始化用户存储空间失败: %s", err.Error()))
			global.APP.DB.Unscoped().Where("username=?", user.Username).Delete(&models.User{}) // 硬删除
			utils.Fail(c, errorx.UserRegister, "用户注册失败")
		} else {
			storage := models.Storage{
				Accesskey:  global.APP.Configuration.Minio.AccessKey,
				Alias:      global.APP.Configuration.Minio.Alias,
				Secretkey:  global.APP.Configuration.Minio.SecretKey,
				Bucketname: global.APP.Configuration.Minio.BucketName,
				Zone:       global.APP.Configuration.Minio.Zone,
				Userid:     int64(user.ID),
				DomainName: "",
			}
			tx := global.APP.DB.Create(&storage).Error
			if tx != nil {
				global.APP.DB.Unscoped().Where("username=?", user.Username).Delete(&models.User{})
				utils.Fail(c, errorx.UserRegister, "用户注册失败")
			} else {
				utils.Success(c, 0, userInfo)
			}
		}
	}
}
